import { Component, OnInit, Inject } from '@angular/core';
import { _HttpClient } from '@delon/theme';
import {UtilityService} from '../../../../service/utils.service';
import {appConfig} from '../../../../service/common';
import {NzModalService, NzNotificationService} from 'ng-zorro-antd';
import {Router} from '@angular/router';
import { DA_SERVICE_TOKEN, ITokenService } from '@delon/auth';
import { ProductModule } from '../../../../service/delivent/projectModule';
import * as _ from 'lodash';
import * as moment from 'moment';
@Component({
  selector: 'app-s-project',
  templateUrl: './s-project.component.html',
  styleUrls: ['./s-project.component.less'],
})
export class SProjectComponent implements OnInit {

    constructor(
        private http: _HttpClient,
        private router: Router,
        private utilityService: UtilityService,
        private modal: NzModalService,
        private nznot: NzNotificationService,
        @Inject(DA_SERVICE_TOKEN) private tokenService: ITokenService,
    ) { }


    // 变量
    isPagination = true; // 是否有分页
    showAdd: boolean; // 是否有修改
    productItem: ProductModule = new  ProductModule(); // 信息
    productAdd: ProductModule = new  ProductModule(); // 信息
    modalVisible = false; // 弹出框 默认关闭
    data: any[] = []; // 表格数据
    headerDate = [  // 配置表头内容
        { label: '工程名称', value: 'projectName', isclick: false },
        { label: '工程类型', value: 'projectType', isclick: false },
        { label: '导出到', value: 'exportShow', isclick: false },
        { label: '部署到', value: 'deployShow', isclick: false },
    ];
    modelTitle: string;
    isEdit = false;
    // 传入按钮层
    moreData = {
        morebutton: true,
        buttonData: [
        ]
    }
    test: string;
    total: number;
    pageTotal: number;
    isShowTotal: boolean;
    isShowbranch: boolean;
    checkmsg: any;
    // 枚举值
    projectType:any[]=[];
    buttons = [
        {key: 'add', value: '新建工程', if: true}
    ];
    token: any; // token值
    exportType: any;
    deployType: any;
    page: any;
    diconArray: any;
    // 部署类型
    diconfig: any = [{
        'exportType': '' ,
        'depolySelect': [{ depoly: ''}],
        'error': false
    }];

    pageIndex=1;
    tag = '验证'

    ngOnInit() {
        // 枚举值赋值
        this.exportType = appConfig.Enumeration.exportType;
        this.deployType = appConfig.Enumeration.deployType;
        this.token  = this.tokenService.get().seniortoken; // 绑定token
        this.showAdd = true;
        this.isShowTotal = true;
        this.getData();
    }
    loading = false;
    expandForm = false;
        listloading = false;
    getData(options?) {
        if (options) {
         this.pageIndex = 1
        }

            this.page = {
                condition: this.productItem,
                page: {
                    current: this.pageIndex,
                    size: 10,
                     orderByField: 'guid',
                     asc: false // asc 默认是true  升序排序，时间类型 用false， 降序

                }
            };
            this.listloading = true;
        this.utilityService.postData(appConfig.testUrl  + appConfig.API.sProjectList , this.page )
            .subscribe(
                (val) => {
                      this.listloading = false;
                    this.data = val.result.records;
                    this.total = val.result.total;

                    this.pageTotal = val.result.pages * 10;
                    _.forEach(this.data , function (value) {
                        if (!_.isUndefined(value.deployConfig)) {
                            if (value.deployConfig !== 'default') {
                                let jsonPar = JSON.parse(value.deployConfig);
                                var str = ''
                                _.forEach(jsonPar , function (json) {
                                    // 把exportType拼接逻辑 如果是空，那就添加exportType
                                    if (str === '') {
                                        str = str + json.exportType;
                                    }else { // 如果不是空，那就中间+,
                                        str = str + ',' + json.exportType;
                                    }
                                    value.exportShow = str;
                                    value.deployShow = json.deployType;
                                });
                            } else {
                                value.deployShow = value.deployConfig;
                                value.exportShow = value.deployConfig;
                            }
                        }
                        value.buttonData = [
                            {key: 'dels', value: '删除'},
                            {key: 'upd', value: '修改'}
                        ];
                    });
                }
                , (error) => {
                       this.listloading = false;
                    this.nznot.create('error', error.code , error.msg);
                }
            );
    }

    // 查询方法
    search() {
        this.getData(this.productItem);
    }

    // 重置
    reset() {
        this.productItem = new ProductModule();
        this.getData();
    }

    // 新增方法
    projectOptions = null;

  _value: any[] = null;

  _console(value) {
    console.log(value);
  }
  exportTypeList = [];
   changePro(item) {
       console.log(item)
       if(!item){
            this.exportTypeList = []
       }else{
           this.projectType.forEach(i=>{
        if(i.value == item){

                  this.exportTypeList = i.children;
           }
       })
       }


  }
  checkbox(status,i){

      i.checked = status
      i.children.forEach(j=>{
          j.checked = i.checked
          if( i.children.length===1){
                    j.disabled = true
          }else{
                j.disabled = false
          }

      })
         console.log(i)
  }
  checkboxChild(status,s,i){

      s.checked = status
      let arr = []
      i.children.forEach(index=>{
             if(s.name === index.name){
                  index = s
             }
             if(index.checked){
                   arr.push(index)
             }

      })
      let obj=true;
      if(arr.length === 1){
            obj = true
        }else{
            obj = false
         }
      i.children.forEach(index=>{
          if(index.checked){
                  index.disabled = obj
          }

            })

  }
  getPatchDeploy(event){

                let check = true
                let disabl = true;
                let childDisabl = true;
                this.utilityService.getData(appConfig.testUrl  +'/sProject/patchDeploy')
                 .subscribe(
                        (val) => {
                            if (val.code === '200') {
                                 this.exportTypeList = [];
                                  this.projectType = [];
                                val.result.forEach(i=>{
                                    if(this.productAdd.projectType === i.name){
                                        this.productAdd.projectType = i.value
                                    }
                                    switch(i.value){
                                      case 'S':
                                      childDisabl = true
                                      disabl = true;
                                      break;
                                      case 'I':
                                      childDisabl = false
                                      disabl = true;
                                      break;
                                      default:
                                      childDisabl = false
                                      disabl = false;
                                      break;
                                    }
                                    if(i.children.length === 1){
                                        disabl = true
                                    }

                                    i.children.forEach(j=>{
                                        j.checked = check;
                                        j.disabled = disabl;
                                     if(j.children.length ===1){
                                              childDisabl = true
                                     }
                                        j.children.forEach(l=>{
                                              l.checked = check;
                                              l.disabled = childDisabl;
                                        })
                                    })

                                    this.projectType.push({key:i.name,value:i.value,children:i.children})

                                })
                              if(this.isEdit){
                                let obj = JSON.parse(event.deployConfig)
                               console.log(obj)
                                let str = []
                                 if(obj.length === 1){
                                        disabl = true
                                    }
                                obj.forEach((i,index)=>{
                                   i.deployType = i.deployType.split(',')
                                    switch(this.productAdd.projectType){
                                      case 'S':
                                      childDisabl = true
                                      disabl = true;
                                      break;
                                      case 'I':
                                      childDisabl = false
                                      disabl = true;
                                      break;
                                      default:
                                      childDisabl = false
                                      disabl = false;
                                      break;
                                    }
                                if(i.deployType.length ===1){
                                     childDisabl = true
                                     }
                                   str = []
                                   i.deployType.forEach(j=>{
                                        str.push({name:j,checked:true,disabled:childDisabl})
                                   })
                                      this.exportTypeList.push({name:i.exportType,checked:true,disabled:disabl,children:str})
                                })
                              }

                                this.isShowbranch = true
                                this.modalVisible = true;
                                // this.productAdd.projectType = 'P'
                             console.log(this.productAdd)
                            }

                        },
                    (error) => {

                            this.nznot.create('error', '', error.msg);

                    }
                    );
  }

    addHandler(event) {
        if (event === 'add') {
             this.modelTitle = '新建工程';
             this.isEdit = false;
             this.productAdd = new ProductModule(); // 清空
             this.getPatchDeploy(event)
        }
    }

    // 验证版本
    checkversion(item) {
           if (this.tag === '通过'){
               return;
           }
         this.utilityService.postData(appConfig.testUrl  + appConfig.API.sBranchadd + '/' + 'path',{svnUrl: item} )
                .subscribe(
                    (val) => {
                        if (val.code === '200') {
                           this.isShowbranch = true
                           this.tag = '通过';
                        }
                    },
                (error) => {

                          this.isShowbranch = false
                          this.checkmsg = error.msg;
                          this.tag  = '验证'
                          this.nznot.create('error', '', error.msg);

                }
                );
        }
       checkagin(item) {
          this.tag  = '验证';
            this.isShowbranch = true
       }



    buttonDataHandler(event) {

    }

    // 翻页方法
    monitorHandler(event) {
        this.pageIndex = event;

          this.getData();
    }


    // 按钮点击事件方法
    buttonEvent(event) {
        if (!_.isNull(event.names)) {
            if (event.names.key === 'upd') {

                this.tag = '验证'
                this.modelTitle = '修改工程';
                // this.productAdd = new ProductModule(); // 清空
                this.productAdd = _.cloneDeep(event);
                this.getPatchDeploy(this.productAdd)
                 console.log(this.productAdd)

                // 深拷贝修改
                // 枚举值转换
                // if (event.projectType === '可选工程') {
                //     event.projectType = 'S';
                // } else if (event.projectType === 'IBS工程') {
                //     event.projectType = 'I';
                // } else {
                //     event.projectType = 'C';
                // }
                // if (event.deployConfig !== 'default') {
                //     this.diconArray =  _.cloneDeep(JSON.parse(event.deployConfig));

                //     for (let i = 0; i < this.diconArray.length; i++ ) {
                //         this.diconArray[i].jsonArray = this.diconArray[i].deployType.split(','); // 字符串转数组
                //         this.diconArray[i].depolySelect = [];
                //         for (let j = 0; j < this.diconArray[i].jsonArray.length; j++) {
                //             let obj = {
                //                 depoly: this.diconArray[i].jsonArray[j]
                //             };
                //             this.diconArray[i].depolySelect.push(obj)
                //         }
                //     }
                //     this.diconfig = this.diconArray;
                // } else {
                //     this. diconfig = [{
                //         'exportType': event.deployConfig ,
                //         'depolySelect': [{ depoly: event.deployConfig}],
                //         'error': false
                //     }];
                // }



                this.modalVisible = true;
                this.isEdit = true;
            } else if (event.names.key === 'dels') { // 删除逻辑
                this.modal.open({
                    title: '删除工程',
                    content: '您是否确定删除该工程?',
                    okText: '确定',
                    cancelText: '取消',
                    onOk: () => {
                        this.utilityService.deleatData(appConfig.testUrl  + appConfig.API.sProject + '/' + event.guid  )
                            .subscribe(
                                (val) => {
                                    this.nznot.create('success', val.msg , val.msg);
                                    if ( !(( this.total - 1) % 10)) {
                                        this.pageIndex -- ;
                                        this.getData();
                                    }

                                    this.getData();
                                }
                            );
                    },
                    onCancel: () => {

                    }
                });

            } else {

            }
        }
    }

    // 选中复选框方法
    selectedRow(event) {

    }

    save() {
        let splicing  = [];
        console.log(this.exportTypeList)
        this.exportTypeList.forEach(i=>{
            if(i.checked===true){
                let arr = []
               i.children.forEach(j=>{
                    if(j.checked===true){
                   arr.push(j.name)
                          }
               })
               splicing.push({exportType:i.name,deployType:arr.join(',')})
            }
        })
        if(splicing.length === 0 || !this.productAdd.projectName || !this.productAdd.projectType || !this.productAdd.fullPath){
            this.nznot.create('error', '信息填写不完整，请检查' , '信息填写不完整，请检查');
            return;
        }
        this.productAdd.deployConfig = JSON.stringify(splicing);
        if (this.isEdit) { // 修改
            this.utilityService.putData(appConfig.testUrl  + appConfig.API.sProject, this.productAdd )
                .subscribe(
                    (val) => {
                        this.nznot.create('success', val.msg , val.msg);
                        this.getData();
                    },
                    error => {
                        this.nznot.create('error', error.code , error.msg);
                    }
                );
        } else {
            this.utilityService.postData(appConfig.testUrl  + appConfig.API.sProject, this.productAdd )
                .subscribe(
                    (val) => {
                        this.nznot.create('success', val.msg , val.msg);
                        this.getData();
                    },
                    error => {
                        this.nznot.create('error', error.code , error.msg);
                    }
                );
        }
        this.modalVisible = false;

    }


    // 取消
    cancel() {
        this.modalVisible = false;
        this.getData(); // 重新查询
    }




    addInput() {
        this.diconfig.push({ 'exportType': '' ,
                            'depolySelect': [{ depoly: ''}],
                            'error': false});
    }


    removeInput(index) {
        let i = this.diconfig.indexOf(index);
        this.diconfig.splice(i, 1);
    }


    addChildInput(items) {
        items.push({ depoly: ''});
    }

    removeChildInput(items, s) {
        let t = items.indexOf(s);
        items.splice(t, 1);
    }


    onblur(item, index, array){
        for (let i = 0; i < array.length; i++) {
            if (index === i) continue; // 本次不判断, 否则会一直跟本次判断，一直true
            if (item.exportType === array[i].exportType) {
                item.error = true;
                return;
            }
        }
        item.error = false;
    }



}
